package com.mcz.yun4book.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mcz.yun4book.entity.Book;
import com.mcz.yun4book.entity.Type;
import com.mcz.yun4book.service.BookService;
import com.mcz.yun4book.service.TypeService;
import com.mcz.yun4book.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private TypeService typeService;

    @RequestMapping(value = "/list",produces = {"application/json"})
    @ResponseBody
    public Result<Book> list(int page,int limit,Book book){
        System.out.println(book);
        Result<Book> result=new Result<>();
        Page<Book> pageInfo=bookService.findAllBook(page, limit,book);
        result.setData(pageInfo.toList());
        result.setCount(pageInfo.getTotalElements());
        return result;
    }

    @GetMapping("list")
    public String toListPage(){

        return "book/list";
}

    @DeleteMapping("del")
    @ResponseBody
    public Result del(int id){
        Result result=new Result<>();
        int ret=bookService.delBookById(id);
        if(ret==0){
            result.setCode(1);
            result.setMsg("删除失败");
        }
        return  result;
    }

    @GetMapping("add")
    public String toAdd(Model model) throws JsonProcessingException {

        List<Type> types=typeService.findAllType();
        model.addAttribute("types",new ObjectMapper().writeValueAsString(types));
        return "book/add";
    }

    @PostMapping("add")
    @ResponseBody
    public Result doAdd(@RequestBody Book book){

        Result result=new Result<>();
        result.setMsg("添加成功");
        Book ret=bookService.addBook(book);
        if(book==null){
            result.setCode(1);
            result.setMsg("添加失败");
        }
        return  result;
    }
    @GetMapping("edit")
    public String toEdit(int id, Model model) throws JsonProcessingException {
        Book book=bookService.findBookId(id);
        //转成JSON格式
        List<Type> types=typeService.findAllType();
        model.addAttribute("types",new ObjectMapper().writeValueAsString(types));
        model.addAttribute("book",new ObjectMapper().writeValueAsString(book));
        return "book/edit";
    }
    @PutMapping("edit")
    @ResponseBody
        public Result doEdit (@RequestBody Book book){

            Result result = new Result<>();
            result.setMsg("编辑成功");
            Book ret = bookService.updateBook(book);
            if (ret == null) {
                result.setCode(1);
                result.setMsg("编辑失败");
            }
            return result;
        }

}


